

package tomkitty;

import java.util.*;
import java.io.*;

public class TkConnectionHandlerPool implements ConnectionHandlerPool {

  private Stack<ConnectionHandler> waiting = new Stack<ConnectionHandler>();
  private Vector<ConnectionHandler> running = new Vector<ConnectionHandler>();
  private Handler handler;
  private AppContext context;
  private Configuration config;
  private int minthreads;
  private int maxthreads;

  public TkConnectionHandlerPool(Handler handler, AppContext context,
      int min, int max) {

    this.handler = handler;
    this.context = context;
    this.config = context.getConfig();
    minthreads = min;
    maxthreads = max;

    waiting.ensureCapacity(minthreads);
    running.ensureCapacity(maxthreads);

    for (int i = 0; i < minthreads; i++) {
      ConnectionHandler h = new TkConnectionHandler(this);
      h.init((handler == null) ? null : handler.clone(), context);
      waiting.push(h);
    }
  }

  public synchronized ConnectionHandler getConnectionHandler() 
    throws TkTooManyThreadsException {

    ConnectionHandler h = null;

    Debug.d("Threads (running): " + running.size());
    Debug.d("Threads (waiting): " + waiting.size());
    Debug.d("");

    if (running.size() < maxthreads) {
      if (waiting.isEmpty()) {
        h = new TkConnectionHandler(this);
        h.init((handler == null) ? null : handler.clone(), context);
      } else {
        h = waiting.pop();
      }

      running.add(h);
    } else {
      throw new TkTooManyThreadsException();
    }

    return h;
  }

  public synchronized void recycle(ConnectionHandler h) {
    running.remove(h);

    if (waiting.size() < minthreads) {
      waiting.push(h);
    }
  }

}
